/*
* Copyright (C) 2008-2009 J-P Nurmi jpnurmi@gmail.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* $Id: mdiarea.cpp 303 2009-02-18 21:35:48Z jpnurmi $
*/

#include "mdiarea.h"
#include <QMdiSubWindow>

MdiArea::MdiArea(QWidget* parent)
	: QMdiArea(parent)
{
	connect(this, SIGNAL(subWindowActivated(QMdiSubWindow*)), 
        this, SLOT(onSubWindowActivated(QMdiSubWindow*)));
}

QWidget* MdiArea::container()
{
    return this;
}

void MdiArea::addView(MessageView* view)
{
	QMdiSubWindow* window = addSubWindow(view);
    window->setAttribute(Qt::WA_DeleteOnClose, false);
    connect(view, SIGNAL(destroyed()), window, SLOT(deleteLater()));
	window->setWindowTitle(view->windowTitle());
	d.subWindows.insert(view, window);
	window->showMaximized();
	view->show();
}

void MdiArea::removeView(MessageView* view)
{
	Q_ASSERT_X(false, "MdiArea::removeView", "TODO");
	d.subWindows.remove(view);
}

QList<MessageView*> MdiArea::takeAllViews()
{
	QList<MessageView*> views;
	foreach (QMdiSubWindow* subWindow, subWindowList())
	{
		views += static_cast<MessageView*>(subWindow->widget());
		removeSubWindow(subWindow);
		subWindow->deleteLater();
	}
	return views;
}

MessageView* MdiArea::currentView()
{
    MessageView* view = 0;
    if (activeSubWindow())
        view = static_cast<MessageView*>(activeSubWindow()->widget());
    return view;
}

void MdiArea::setCurrentView(MessageView* view)
{
    if (!d.subWindows.contains(view))
    {
        qWarning("MdiArea::setCurrentView unknown view?");
        return;
    }
    setActiveSubWindow(d.subWindows.value(view));
}

void MdiArea::onSubWindowActivated(QMdiSubWindow* subWindow)
{
	if (subWindow && subWindow->widget())
        emit currentViewChanged(static_cast<MessageView*>(subWindow->widget()));
}
